package com.pmcc.cj.service;

import com.pmcc.cj.entity.*;
import com.pmcc.cj.entity.vo.CustomerVo;
import com.pmcc.cj.repository.*;
import com.pmcc.cj.vo.CarouselVo;
import com.pmcc.cj.vo.CertificationVo;
import com.pmcc.cj.vo.RetailerVo;
import com.pmcc.core.config.security.JwtAuthenticationRequest;
import com.pmcc.core.entity.SmsRecord;
import com.pmcc.core.repository.SmsRecordRepository;
import com.pmcc.core.service.JwtAuthenticationResponse;
import com.pmcc.core.service.LoginService;
import com.pmcc.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.regexp.internal.RE;
import net.sf.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.mobile.device.Device;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tomas on 2020/9/21.
 */
@Transactional
@Service
public class AppService {
    private static String appId = SystemPropertyUtil.getProperty("appId");
    private static String appSecret = SystemPropertyUtil.getProperty("appSecret");
    private Integer[] distance={10000*1000,5000*1000,2000*1000,1000*1000,500*1000,200*1000,100*1000,50*1000,
                25*1000,20*1000,10*1000,5000,2000,1000,500,200,100,50,20};
    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    CjPositionRepository cjPositionRepository;
    @Autowired
    LoginService loginService;
    @Autowired
    CjCarouselRepository cjCarouselRepository;
    @Autowired
    CjCommodityRepository cjCommodityRepository;
    @Autowired
    CjCommodityYunRepository cjCommodityYunRepository;
    @Autowired
    CjShoppingCartRepository cjShoppingCartRepository;
    @Autowired
    CjTrainDetailRepository cjTrainDetailRepository;
    @Autowired
    CjRobotTaskRepository cjRobotTaskRepository;
    @Autowired
    CjOrderRepository cjOrderRepository;
    @Autowired
    CjActivationSaleRepository cjActivationSaleRepository;
    @Autowired
    CjAreaAgencyRepository cjAreaAgencyRepository;
    @Autowired
    CjCountyProxyRepository cjCountyProxyRepository;
    @Autowired
    CjRetailerRepository cjRetailerRepository;
    @Autowired
    CjShoppingCartDetailRepository cjShoppingCartDetailRepository;
    @Autowired
    SmsRecordRepository smsRecordRepository;
    @Autowired
    CjTaskRepository cjTaskRepository;
    @Autowired
    CjFarmRepository farmRepository;
    @Autowired
    CjMoneyRecordRepository cjMoneyRecordRepository;
    @Autowired
    CjCountyVillageRepository cjCountyVillageRepository;


    public ResultBean addCustomer(CjCustomer model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            if(StringUtil.isEmpty(model.getWechatId())){
                resultBean.setResultCode(ResultBean.FAIL);
                return resultBean;
            }else {
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                model.setProxy(0);
                model.setLastLoginTime(new Date());
                model.setEnabled("0");
                model.setDelFlag(0);
                model.setCreateTime(new Date());
                model.setUserName(model.getWechatId());
                model.setPassword(encoder.encode("123456"));
                model.setRoleId("000000006e1037b4016e3aa73a48871b");//默认角色为客户
                cjCustomerRepository.saveAndFlush(model);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean addPosition(CjPosition model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            cjPositionRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean wechatLogin(String code,Device device){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            // 第1步：通过code换取网页授权access_token
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId +
                    "&secret=" + appSecret +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            JSONObject jsonObject = HttpClientUtils.doGet(url);
            String openid = jsonObject.getString("openid");
            String access_Token = jsonObject.getString("access_token");

            //第2步：判断库里是否存在，如果存在则不需要请求用户信息，如果禁用直接返回
            CjCustomer customer = cjCustomerRepository.findByAndWechatId(openid);
            if(customer != null){
                //表示已禁用
                if(customer.getDelFlag()==1){
                    resultBean.setResultCode(ResultBean.DISABLED);
                    return resultBean;
                }else {
                    customer.setLastLoginTime(new Date());
                    cjCustomerRepository.saveAndFlush(customer);
                }
            }else {
                // 第3步：拉取用户信息(需scope为 snsapi_userinfo)
                url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token +
                        "&openid=" + openid +
                        "&lang=zh_CN";
                JSONObject userInfoJson = HttpClientUtils.doGet(url);
                CjCustomer cjCustomer = new CjCustomer();
                cjCustomer.setWechatId(openid);
                cjCustomer.setWechatName(userInfoJson.getString("nickname"));
                cjCustomer.setWechatImage(userInfoJson.getString("headimgurl"));
                cjCustomer.setSex(userInfoJson.getInteger("sex"));
                cjCustomer.setUserName(openid+"&*&*&*&*&*&*&*&*&*&*");
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                cjCustomer.setPassword(encoder.encode("123456"));
                cjCustomer.setCardAuth(false);
                cjCustomer.setDriverAuth(false);
                cjCustomer.setRetailer(0);
                cjCustomer.setProxy(0);
                cjCustomer.setLastLoginTime(new Date());
                cjCustomer.setEnabled("0");
                cjCustomer.setCreateTime(new Date());
                cjCustomer.setDelFlag(0);
                cjCustomer.setMoney(new BigDecimal("0"));
                cjCustomer.setFreezeMoney(new BigDecimal("0"));
                //设置默认提现密码是123456
                cjCustomer.setCashPassword(encoder.encode("123456"));
                cjCustomer.setRoleId("000000006e1037b4016e3aa73a48871b");
                cjCustomer.setPayFlag(0);
                cjCustomer.setRobotFlag(0);//默认推送
                cjCustomerRepository.saveAndFlush(cjCustomer);
            }
//            openid="oOz7F56Y-jY8zBDXF-Q9Y-8mXzXs";
            //第4步：根据微信id获取token
            JwtAuthenticationResponse jwtAuthenticationResponse= loginService.login(new JwtAuthenticationRequest(openid,"123456"),device,"&*&*&*&*&*&*&*&*&*&*");
            resultBean.setObject(jwtAuthenticationResponse);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean queryCommodityByPage(CjCommodity model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page = cjCommodityRepository.findAll(this.getCommoditySpecification(model), antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjCommodity> getCommoditySpecification(CjCommodity model) {
        return new Specification<CjCommodity>() {
            @Override
            public Predicate toPredicate(Root<CjCommodity> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                //名称
                if(StringUtil.isNotEmpty(model.getName())){
                    list.add(builder.like(root.get("name").as(String.class),  "%"+model.getName().trim()+"%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean getCarousel(Integer carouselType){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjCarousel> list=cjCarouselRepository.findByCarouselTypeOrderBySequenceAsc(carouselType);
            List<CarouselVo> alist=new ArrayList<>();
            for(CjCarousel cc:list){
                CarouselVo cv=new CarouselVo(cc.getId(),cc.getAddress(),cc.getProductTitle());
                alist.add(cv);
            }
            resultBean.setRows(alist);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean getCarouselDetail(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCarousel cjCarousel=cjCarouselRepository.findOne(id);
            resultBean.setObject(cjCarousel);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean addShopping(CjShoppingCart model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            model=cjShoppingCartRepository.saveAndFlush(model);
            if(StringUtil.isNotEmpty(model.getJsonData())){
                List<CjShoppingCartDetail> list = (List<CjShoppingCartDetail>) JSONArray.toCollection(JSONArray.fromObject(model.getJsonData()),CjShoppingCartDetail.class);
                if(list != null && list.size()>0){
                    for(CjShoppingCartDetail shoppingCartDetail : list){
                        shoppingCartDetail.setShoppingCartId(model.getId());
                        cjShoppingCartDetailRepository.saveAndFlush(shoppingCartDetail);
                    }
                }
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean deleteShoppingCart(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjShoppingCartDetail> list=cjShoppingCartDetailRepository.findByShoppingCartId(id);
            if(list != null && list.size()>0){
                for(CjShoppingCartDetail shoppingCartDetail:list){
                    cjShoppingCartDetailRepository.delete(shoppingCartDetail);
                }
            }
            cjShoppingCartRepository.delete(id);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean findShopping(){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjShoppingCart> list = cjShoppingCartRepository.findByEmployeeId(OnlineUser.getEmployeeId());
            if(list != null && list.size()>0){
                for(CjShoppingCart shoppingCart : list){
                    CjCommodityYun cjCommodityYun = cjCommodityYunRepository.findOne(shoppingCart.getCommodityId());
                    shoppingCart.setName(cjCommodityYun.getName());
                    shoppingCart.setCommodityYunImage(cjCommodityYun.getAddress() != null ? cjCommodityYun.getAddress() :"");
                    List<CjShoppingCartDetail> details=cjShoppingCartDetailRepository.findByShoppingCartId(shoppingCart.getId());
                    shoppingCart.setDetailList(details);
                }
            }
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean getCustomer(String customerId){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCustomer customer = new CjCustomer();
            if(StringUtil.isNotEmpty(customerId)){
                customer = cjCustomerRepository.findOne(customerId);
            }else {
                customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
            }
            resultBean.setObject(customer);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean submitTrain(String trainId){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCustomer customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
            CjTrainDetail cjTrainDetail=cjTrainDetailRepository.findByTrainIdAndEmployeeId(trainId,OnlineUser.getEmployeeId());
            if(cjTrainDetail != null){
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("已经报名，不能重复报名");
                return resultBean;
            }else {
                cjTrainDetail =new CjTrainDetail();
                cjTrainDetail.setName(customer.getCardName());
                cjTrainDetail.setCreateTime(new Date());
                cjTrainDetail.setTrainId(trainId);
                cjTrainDetail.setEmployeeId(OnlineUser.getEmployeeId());
                cjTrainDetail.setCellphone(customer.getCellphone());
                cjTrainDetailRepository.saveAndFlush(cjTrainDetail);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean updateCustomer(CjCustomer model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCustomer customer = cjCustomerRepository.findOne(model.getId());
            BeanUtils.copyProperties(model, customer);
            cjCustomerRepository.saveAndFlush(customer);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean updateCustomerByCellphone(String id, String cellphone, String code, String p1, String p2, String p3, String p4, String p5,String p6){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            SmsRecord smsRecord = smsRecordRepository.findFirstByTelephoneOrderByCreateTimeDesc(cellphone);
            if(smsRecord != null){
                int num=DateUtil.betweenOfMinute(smsRecord.getCreateTime(),new Date());
                if(num<=3){
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(smsRecord.getMessage());
                    String str = jsonObject.getString("code");
                    if(!str.equals(code)){
                        resultBean.setResultCode(ResultBean.FAIL);
                        resultBean.setResultDesc("验证码错误");
                        return resultBean;
                    }
                }else {
                    resultBean.setResultCode(ResultBean.FAIL);
                    resultBean.setResultDesc("验证码过期");
                    return resultBean;
                }
            }else {
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("请重新获取验证码");
                return resultBean;
            }
            CjCustomer customer = cjCustomerRepository.findOne(id);
            if(customer != null){
                customer.setCellphone(cellphone);
                customer.setProvince(p1);
                customer.setCity(p2);
                customer.setCounty(p3);
                customer.setTownship(p4);
                customer.setVillage(p5);
                customer.setAddress(p6);
                customer.setCardAuth(true);
                cjCustomerRepository.saveAndFlush(customer);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean addRobotTask(CjRobotTask model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCustomer customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
            model.setBeginTime( DateUtil.StringToDate(model.getBegin(),DateUtil.YYYY_MM_DD));
            model.setCustomerId(customer.getId());
            model.setCustomerName(customer.getCardName());
            model.setCellphone(customer.getCellphone());
            model.setFettle(0);
            model.setIssued(false);
            model.setCreateTime(new Date());
            cjRobotTaskRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean queryRobotTask(AntdPage antdPage){
        ResultBean resultBean= new ResultBean(ResultBean.SUCCESS);
        try {
            CjRobotTask task=new CjRobotTask();
            task.setFettle(0);
            Page page=cjRobotTaskRepository.findAll(this.getTaskSpecification(task),antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    private Specification<CjRobotTask> getTaskSpecification(CjRobotTask model) {
        return new Specification<CjRobotTask>() {
            @Override
            public Predicate toPredicate(Root<CjRobotTask> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(model.getFettle()!= null){
                    list.add(builder.equal(root.get("fettle").as(Integer.class),  model.getFettle()));
                }

                Predicate[] p = new Predicate[list.size()];
                query.where(list.toArray(p));
                query.orderBy(builder.desc(root.get("createTime").as(Date.class)));
                return builder.and(list.toArray(p));
            }
        };
    }

    public ResultBean robotTaskAccept(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjTask task=cjTaskRepository.findOne(id);
            task.setFettleTask(0);
            task.setRobotConfirm(0);//机手进入开始作业状态
            task.setFettleType(1);//机手接单之后就不需要推送了
            cjTaskRepository.saveAndFlush(task);
            //修改对应订单表状态
            CjOrder order = cjOrderRepository.findOne(task.getOrderId());
            order.setOrderStatus(2);
            order.setRobotId(OnlineUser.getEmployeeId());
            cjOrderRepository.saveAndFlush(order);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean robotTaskFinish(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjRobotTask robotTask=cjRobotTaskRepository.findOne(id);
            robotTask.setRobotId(OnlineUser.getEmployeeId());
            robotTask.setFettle(1);
            robotTask=cjRobotTaskRepository.saveAndFlush(robotTask);
            //接单之后把订单添加到任务表
            CjTask cjTask = new CjTask();
            cjTask.setRobotTaskId(robotTask.getId());
            cjTask.setFettle(0);
            cjTask.setRobotId(robotTask.getRobotId());
            cjTask.setCustomerId(robotTask.getCustomerId());
            cjTask.setCustomerName(robotTask.getCustomerName());
            cjTask.setCellphone(robotTask.getCellphone());
            cjTask.setFettleTask(0);
            cjTask.setCreateTime(new Date());
            cjTask.setFettleType(1);
            cjTask.setProvince(robotTask.getProvince());
            cjTask.setCity(robotTask.getCity());
            cjTask.setCounty(robotTask.getCounty());
            cjTask.setAddress(robotTask.getAddress());
            cjTask.setSalesmanId(robotTask.getSalesmanId());
            cjTask.setXx(robotTask.getXx());
            cjTask.setYy(robotTask.getYy());
            cjTask.setMoney(robotTask.getMoney());
            cjTask.setNumber(robotTask.getNumber());
            cjTask.setCycleTime(robotTask.getCycleTime());
            cjTask.setCropType(robotTask.getCropType());
            cjTask.setMedicineType(robotTask.getMedicineType());
            cjTask.setBeginTime(robotTask.getBeginTime());
            cjTask.setRemark(robotTask.getRemark());
            cjTask.setRobotConfirm(0);
            cjTask.setRobotFlag("0");
            cjTaskRepository.saveAndFlush(cjTask);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
//    public ResultBean selectOrder(String flag){
//        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
//        try {
//            List<CjOrder> list = new ArrayList<>();
//            switch (flag){
//                case "1":
//                    list = cjOrderRepository.findByEmployeeIdAndOrderStatus(OnlineUser.getEmployeeId(),1);
//                    break;
//                case "2":
//                    list = cjOrderRepository.findByEmployeeIdAndOrderStatus(OnlineUser.getEmployeeId(),2);
//                    break;
//            }
//            resultBean.setRows(list);
//        }catch (Exception e){
//            resultBean.setResultCode(ResultBean.FAIL);
//        }
//        return resultBean;
//    }

    public ResultBean verificationCode(String code,String type){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            String pro="";//省
            String city="";//市
            String cou="";//县
            String xiang="";//乡
            String cun="";//村
            CjAreaAgency areaAgency=cjAreaAgencyRepository.findByActivationCodeAndDelFlag(code,0);
            resultBean.setResultData("有效");
            if(areaAgency == null){
                resultBean.setResultData("无效");
                resultBean.setResultCode(ResultBean.FAIL);
            }else {
                if("0".equals(type)){
                    if(areaAgency.getLevel() != 5){
                        resultBean.setResultData("无效");
                        resultBean.setResultCode(ResultBean.FAIL);
                    }else {
                        cun = areaAgency.getAddress();
                        CjAreaAgency c1= cjAreaAgencyRepository.findOne(areaAgency.getParentId());
                        xiang = c1.getAddress();
                        CjAreaAgency c2= cjAreaAgencyRepository.findOne(c1.getParentId());
                        cou = c2.getAddress();
                        CjAreaAgency c3= cjAreaAgencyRepository.findOne(c2.getParentId());
                        city = c3.getAddress();
                        CjAreaAgency c4= cjAreaAgencyRepository.findOne(c3.getParentId());
                        pro = c4.getAddress();
                    }
                }else if("1".equals(type)){
                    if(areaAgency.getLevel() != 3){
                        resultBean.setResultData("无效");
                        resultBean.setResultCode(ResultBean.FAIL);
                    }else {
                        cou = areaAgency.getAddress();
                        CjAreaAgency c1= cjAreaAgencyRepository.findOne(areaAgency.getParentId());
                        city = c1.getAddress();
                        CjAreaAgency c2= cjAreaAgencyRepository.findOne(c1.getParentId());
                        pro = c2.getAddress();
                    }
                }
                resultBean.setResultDesc(pro+city+cou+xiang+cun);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean certificationCustomer(CertificationVo certificationVo){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            if(certificationVo.getType() ==0) {
                CjRetailer retailer = new CjRetailer();
                BeanUtils.copyProperties(certificationVo,retailer);
                retailer.setFettle(0);
                retailer.setSubmitTime(new Date());
                cjRetailerRepository.saveAndFlush(retailer);
            }else {
                CjCountyProxy countyProxy = new CjCountyProxy();
                BeanUtils.copyProperties(certificationVo,countyProxy);
                countyProxy.setFettle(0);
                countyProxy.setSubmitTime(new Date());
                cjCountyProxyRepository.saveAndFlush(countyProxy);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean getRetailer(){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjRetailer retailer = cjRetailerRepository.findByEmployeeId(OnlineUser.getEmployeeId());
            if(retailer !=null){
                resultBean.setObject(retailer);
            }else{
                resultBean.setResultCode(ResultBean.FAIL);
            }

        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean getCountyProxy(){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCountyProxy proxy=cjCountyProxyRepository.findByEmployeeId(OnlineUser.getEmployeeId());
            if(proxy !=null){
                resultBean.setObject(proxy);
            }else{
                resultBean.setResultCode(ResultBean.FAIL);
            }

        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 种地大户认证
     * @param id
     * @param cardId
     * @param cardImage1
     * @param cardImage2
     * @return
     */
    public ResultBean verificationFarm(String id, String code,String cardId, String cardImage1, String cardImage2) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjFarm farm=new CjFarm();
            farm.setCardId(cardId);
            farm.setCode(code);
            farm.setEmployeeId(id);
            CjCustomer cjCustomer=cjCustomerRepository.findOne(id);
            farm.setName(cjCustomer.getWechatName());
            farm.setImage1Id(cardImage1);
            farm.setImage2Id(cardImage2);
            farm.setVerifyResult(0);
            farm.setSubmitTime(new Date());
            //根据code查询业务员的id和姓名
           CjActivationSale cas= cjActivationSaleRepository.findByActivationCodeAndCodeTypeAndUseFlagAndDelFlag(code,1,0,0);
           if(cas!=null){
               farm.setSalesmanId(cas.getEmployeeId());
               farm.setSalesmanName(cas.getEmployeeName());
               farmRepository.save(farm);
               resultBean.setObject(farm);
           }else{
               resultBean.setResultCode(ResultBean.FAIL);
               resultBean.setResultDesc("该认证码已经失效");
           }

        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("后台数据错误，请联系管理员");
        }
        return resultBean;
    }

    /**
     * 验证种地大户的激活码是否有效
     * @param code
     * @return
     */
    public ResultBean verificationFarmCode(String code) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        CjActivationSale cas= cjActivationSaleRepository.findByActivationCodeAndCodeTypeAndUseFlagAndDelFlag(code,1,0,0);
        if(cas!=null){
            resultBean.setResultDesc("该认证码有效");
        }else{
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("该认证码已经失效");
        }
        return resultBean;
    }

    /**
     * 查询种地大户是否有填报记录
     * @param id
     * @return
     */
    public ResultBean getFarm(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        CjFarm cjFarm= farmRepository.findByEmployeeId(id);
        if(cjFarm!=null){
            resultBean.setObject(cjFarm);
        }else{
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("无认证填报记录");
        }
        return resultBean;
    }
    public ResultBean personWallet(){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CustomerVo customerVo = new CustomerVo();
            //昨天收益
            BigDecimal yest = new BigDecimal("0");
            CjCustomer customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
            List<CjMoneyRecord> lt= cjMoneyRecordRepository.findByCustomerBelongIdOrderByCreateDateDesc(OnlineUser.getEmployeeId());
            List<CjMoneyRecord> ls= cjMoneyRecordRepository.findByCustomerBelongIdAndFettleAndCreateDateBetweenOrderByCreateDateDesc(OnlineUser.getEmployeeId(),1,DateUtil.getStartDayTime(new Date()),DateUtil.getEndDayTime(new Date()));
            if(ls != null && ls.size()>0){
                for(CjMoneyRecord moneyRecord:ls){
                    yest=yest.add(moneyRecord.getMoney());
                }
            }
            customerVo.setLastMoney(customer.getMoney());
            customerVo.setYest(yest);
            customerVo.setMoneyRecords(lt);
            resultBean.setObject(customerVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean placeAnOrder(){
        ResultBean resultBean= new ResultBean(ResultBean.FAIL);
        try {
//            CjCustomer customer = cjCustomerRepository.findOne(OnlineUser.getEmployeeId());
            //获取当前登录人最后的一条地址信息记录
            List<CjPosition> lis=cjPositionRepository.findByCustomerIdOrderByCreateTimeDesc(OnlineUser.getEmployeeId());
            CjCountyVillage cjCountyVillage1=cjCountyVillageRepository.findByFettleAndAddressAndCounty(0,lis.get(0).getStreet(),lis.get(0).getCounty());
            if(cjCountyVillage1 == null){
                resultBean.setResultDesc("本地区没有零售商");
                return resultBean;
            }
            CjCountyVillage cjCountyVillage2=cjCountyVillageRepository.findByFettleAndAddress(1,lis.get(0).getCounty());
            if(cjCountyVillage2 == null){
                resultBean.setResultDesc("本地区没有县级代理");
                return resultBean;
            }
            List<CjCustomer> list=cjCustomerRepository.findByCountyAndIsDriverAuthAndRobotFlagAndIntegralNotNullOrderByIntegralDesc(lis.get(0).getCounty(),true,0);
            if(list != null && list.size()>0){
                resultBean.setResultCode(ResultBean.SUCCESS);
            }else {
                resultBean.setResultDesc("本地区没有机手接单");
            }
        }catch (Exception e){

        }
        return resultBean;
    }

    public ResultBean getMap(double xx,double yy,Integer size){
        ResultBean resultBean = new ResultBean();
        try {
            List<RetailerVo> lt = new ArrayList<>();
            int num = distance[size-1];//米
            List<CjRetailer> list=cjRetailerRepository.findByFettle(1);
            if(list != null && list.size()>0){
                for(CjRetailer retailer: list){
                    double number=LocationUtils.getDistance(xx,yy,retailer.getXx(),retailer.getYy());
                    if(number <= num){
                        CjCustomer customer = cjCustomerRepository.findOne(retailer.getEmployeeId());
                        RetailerVo retailerVo = new RetailerVo();
                        BeanUtils.copyProperties(retailer,retailerVo);
                        retailerVo.setCellphone(customer.getCellphone());
                        retailerVo.setAddress(customer.getProvince()+customer.getCity()+customer.getCounty()+customer.getTownship()+customer.getVillage()+customer.getAddress());
                        lt.add(retailerVo);
                    }
                }
            }
            resultBean.setRows(lt);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
